package com.blb.zycommunity.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blb.zycommunity.entity.ResponseResult;
import com.blb.zycommunity.entity.SysUser;
import com.blb.zycommunity.service.ISysUserPostService;
import com.blb.zycommunity.service.ISysUserRoleService;
import com.blb.zycommunity.service.ISysUserService;
import com.blb.zycommunity.utils.ExcelDownloadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import static net.sf.jsqlparser.parser.feature.Feature.update;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author chenheng
 * @since 2023-11-20
 */
@RestController
@CrossOrigin
public class SysUserController {


    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserPostService userPostService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Autowired
    private ISysUserService sysUserService;



    @GetMapping("/user-pages")
    public ResponseResult<IPage<SysUser>> findUserPage(@RequestParam(required = false,defaultValue = "1") Long current,
                                                       @RequestParam(required = false,defaultValue = "5") Long size,
                                                       @RequestParam(required = false) String deptName,
                                                       @RequestParam(required = false) String status,
                                                       @RequestParam(required = false) String phonenumber,
                                                       @RequestParam(required = false) String userName,
                                                       @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                                                       @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime finishTime){
        IPage<SysUser> userPage = userService.findUserPage(current, size, deptName, status,  userName,  phonenumber,  startTime, finishTime);
        return ResponseResult.ok(userPage);
    }


    @GetMapping("/user-get/{username}")
    public ResponseResult<SysUser> findByUserName(@PathVariable String username){
        List<SysUser> sysUsers = userService.findInformationByUsername(username);
        return ResponseResult.ok(sysUsers);
    }
    @GetMapping("/post-byUserId")
    public ResponseResult<List<SysUser>> findPostByUserId(@RequestParam Long userId){
        List<SysUser> posts = userService.findPostByUserId(userId);
        return ResponseResult.ok(posts);
    }

    @GetMapping("/role-byUserId")
    public ResponseResult<List<SysUser>> findRoleByUserId(@RequestParam Long userId){
        List<SysUser> roles = userService.findRoleByUserId(userId);
        return ResponseResult.ok(roles);
    }

    @PutMapping("/user-status")
    public ResponseResult updateUserStatus(@RequestParam String status, @RequestParam Long userId){
        return ResponseResult.ok(userService.updateUserStatus(status,userId));
    }

    @GetMapping("/user-sex")
    public ResponseResult<List<SysUser>> findUserSex(){
        List<SysUser> userSex = userService.findUserSex();
        return ResponseResult.ok(userSex);
    }

    @PutMapping("/user")
    public ResponseResult updateUser(@RequestBody SysUser sysUser){
        sysUser.setUpdateTime(LocalDateTime.now());
        return ResponseResult.ok(userService.updateById(sysUser));
    }

    @PostMapping("/user")
    public ResponseResult addUser(@RequestBody SysUser sysUser){
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        userService.save(sysUser);
        return ResponseResult.ok(userService.getById(sysUser.getUserId()));
    }

    @DeleteMapping("/user/{userId}")
    public ResponseResult deleteUser(@PathVariable Long userId){
        userPostService.removePostByUserId(userId);
        userRoleService.removeRoleByUserId(userId);
        userService.removeUser(userId);
        return ResponseResult.ok("ok");
    }

    @DeleteMapping("/users/{userIds}")
    public ResponseResult deleteUsers(@PathVariable List<Long> userIds){
        for (Long userId : userIds) {
            userPostService.removePostByUserId(userId);
            userRoleService.removeRoleByUserId(userId);
        }
        userService.batchDeleteUser(userIds);
        return ResponseResult.ok("ok");
    }

    @PutMapping("/user-password")
    public ResponseResult updateUser(String password, Long userId){
        password = bCryptPasswordEncoder.encode(password);
        return ResponseResult.ok(userService.updateUserPassword(password,userId));
    }



    @PutMapping("/user-edit")
    public ResponseResult<SysUser> editByUserName(SysUser user){
        boolean update = sysUserService.updateById(user);
        return ResponseResult.ok(update);
    }

    /**
     * 获取ip
     * @return
     */
    private String getClientIP() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            return principal.toString();
        }
    }

    @PutMapping("/user-loginTime")
    public ResponseResult<SysUser> setUserLoginTime(SysUser user){
        SysUser user1 = sysUserService.getUserByUsername(user.getUserName());
        user1.setLoginDate(LocalDateTime.now());
        user1.setLoginIp(getClientIP());
        boolean update = sysUserService.updateById(user1);
        return ResponseResult.ok(update);
    }

    @PutMapping("/user-edit-word")
    @Transactional
    public ResponseResult<SysUser> editUser(@RequestBody SysUser user){
        boolean update = sysUserService.updateById(user);
        return ResponseResult.ok(update);
    }

    @PutMapping("/user-edit-password")
    @Transactional
    public ResponseResult<SysUser> editUserPassword(@RequestParam String userName,
                                                    @RequestParam String password,
                                                    @RequestParam String newPassword) throws Exception {
        SysUser user = sysUserService.getUserByUsername(userName);
        String codePassword = user.getPassword();
        //判断输入的原密码和加密后的密码是否一致
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        boolean matches = bc.matches(password,codePassword);
        if(matches){
            user.setPassword(bCryptPasswordEncoder.encode(newPassword));
            boolean update = sysUserService.updateById(user);
        }else {
            //提示密码修改失败
            return  ResponseResult.error(403L,"旧密码错误");
        }
        return ResponseResult.ok(update);
    }

    /**
     * 根据id导出数据
     * @param response
     * @param ids
     * @param filename
     * @throws IOException
     */
    @GetMapping("downloads-user")
    public void exports(
            HttpServletResponse response,
            @RequestParam("ids") long[] ids,
            @RequestParam("filename") String filename) throws IOException {
        System.out.println(filename);
        //List<Long> list = ExcelDownloadUtil.toList(ids);
        List<SysUser> sysUsers = new ArrayList<>();

        for (Long id : ids) {
            SysUser sysUser = userService.excelUserById(id);
            sysUsers.add(sysUser);
        }

        sysUsers.forEach(System.out::println);
        ExcelDownloadUtil.excelDownload(response, filename, SysUser.class, sysUsers);
    }
}